import time
import requests
import binascii
from pyDes import des, ECB, PAD_PKCS5


def get_lt_from_key_passoword(key, pwd):
    # key = "LT-333068-cON2IFQErkQehqTr79Ig60cggM9ECx-http://211.86.241.149:8080/cas"
    a = des("11111111", ECB, pad=None, padmode=PAD_PKCS5)
    a.setKey(key)
    secret_bytes = a.encrypt(pwd, padmode=PAD_PKCS5)

    res = binascii.b2a_base64(secret_bytes).decode("utf-8")
    return res[:-1]


def get_cookie_from_username_passwd(username, password):
    try:
        login_url = "http://uaap.aufe.edu.cn/cas/login?service=http%3A%2F%2Fjwcxk2.aufe.edu.cn%2Fj_spring_cas_security_check"
        login_url_response = requests.get(login_url, timeout=1.5)

        keyHex = login_url_response.text.split("CryptoJS.enc.Utf8.parse('")[1].split("');")[0]
        lt = get_lt_from_key_passoword(key=keyHex, pwd=password)

        login_post_header = {
            'Cookie': 'JSESSIONID={}'.format(login_url_response.cookies.get_dict()["JSESSIONID"])
        }

        login_post_data = {
            "username": username,
            "password": lt,
            "authCode": "",
            "lt": keyHex,
            "execution": "e1s1",
            "_eventId": "submit",
            "isQrSubmit": "false",
            "qrValue": "",
            "isMobileLogin": "false"
        }
        login_post_url_response = requests.post(login_url, headers=login_post_header, data=login_post_data,
                                                allow_redirects=False, timeout=1.5)

        get_cookie_url = login_post_url_response.headers["Location"]

        time.sleep(1)
        get_cookie_url_response = requests.get(get_cookie_url, allow_redirects=False, timeout=1.5)
        cookie_str = "JSESSIONID=" + get_cookie_url_response.cookies.get_dict()["JSESSIONID"]

        return cookie_str
    except:
        return "error"
